package models

import (
	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// GroupBuyActivity 团购活动模型
type GroupBuyActivity struct {
	BaseModel
	Name             string  `orm:"size(100)" json:"name"`
	Image            string  `orm:"size(255)" json:"image"`
	Description      string  `orm:"size(500)" json:"description"`
	OriginalPrice    float64 `orm:"digits(10);decimals(2)" json:"original_price"`   // 原价
	GroupPrice       float64 `orm:"digits(10);decimals(2)" json:"group_price"`      // 团购价
	StartTime        int64   `orm:"" json:"start_time"`                             // 开始时间
	EndTime          int64   `orm:"" json:"end_time"`                               // 结束时间
	MinMembers       int     `orm:"default(2)" json:"min_members"`                  // 最少参团人数
	MaxMembers       int     `orm:"default(0)" json:"max_members"`                  // 最大参团人数，0表示不限
	LimitPerMember   int     `orm:"default(1)" json:"limit_per_member"`             // 每人限购数量
	SoldCount        int     `orm:"default(0)" json:"sold_count"`                   // 已售数量
	Status           int8    `orm:"default(1)" json:"status"`                       // 1:正常, 0:禁用
	SortOrder        int     `orm:"default(0)" json:"sort_order"`                   // 排序
	DeductibleHours  float64 `orm:"digits(10);decimals(2)" json:"deductible_hours"` // 可抵扣时长（小时）
	ApplicableStores string  `orm:"type(text)" json:"applicable_stores"`            // 可用门店ID列表, JSON string
	ApplicableVenues string  `orm:"type(text)" json:"applicable_venues"`            // 可用场地ID列表, JSON string
	AvailableWeekdays string  `orm:"type(text)" json:"available_weekdays"`           // 可用星期, JSON string of numbers (e.g., [1,2,3])
	AvailableTimes    string  `orm:"type(text)" json:"available_times"`              // 可用时段, JSON string of objects (e.g., [{"start_time":"09:00","end_time":"12:00"}])
	SupportBalance   bool    `orm:"default(false)" json:"support_balance"`          // 是否支持余额支付
}

// TableName 设置表名
func (g *GroupBuyActivity) TableName() string {
	return "ss_group_buy_activity"
}

// GetGroupBuyActivityById 根据ID获取团购活动信息
func GetGroupBuyActivityById(id int64) (*GroupBuyActivity, error) {
	activity := &GroupBuyActivity{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(activity)
	return activity, err
}

// GetGroupBuyActivityList 获取团购活动列表
func GetGroupBuyActivityList(page, pageSize int, filters map[string]interface{}) ([]*GroupBuyActivity, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(GroupBuyActivity))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if franchiseId, ok := filters["franchise_id"].(int64); ok {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var activities []*GroupBuyActivity
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&activities)

	return activities, total, err
}

// CreateGroupBuyActivity 创建团购活动
func CreateGroupBuyActivity(activity *GroupBuyActivity) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(activity)
	return id, err
}

// UpdateGroupBuyActivity 更新团购活动信息
func UpdateGroupBuyActivity(activity *GroupBuyActivity) error {
	o := orm.NewOrm()
	_, err := o.Update(activity, "Name", "Image", "Description", "OriginalPrice",
		"GroupPrice", "StartTime", "EndTime", "MinMembers", "MaxMembers",
		"LimitPerMember", "Status", "SortOrder",
		"DeductibleHours", "ApplicableVenues", "ApplicableStores",
		"AvailableWeekdays", "AvailableTimes",
		"UpdatedBy", "UpdatedAt", "FranchiseId", "SupportBalance")
	return err
}

// DeleteGroupBuyActivity 删除团购活动（软删除）
func DeleteGroupBuyActivity(id int64) error {
	o := orm.NewOrm()
	activity := &GroupBuyActivity{BaseModel: BaseModel{Id: id}}
	if err := o.Read(activity); err != nil {
		return err
	}

	activity.IsDeleted = 1
	_, err := o.Update(activity, "IsDeleted")
	return err
}

// GetActiveGroupBuyActivities 获取当前有效的团购活动
func GetActiveGroupBuyActivities(storeId int64, franchiseId int64) ([]*GroupBuyActivity, error) {
	o := orm.NewOrm()
	var activities []*GroupBuyActivity

	cond := orm.NewCondition().And("status", 1).And("is_deleted", 0)

	if franchiseId > 0 {
		cond = cond.And("franchise_id", franchiseId)
	}

	// 检查时间范围
	now := time.Now().Unix()
	cond = cond.And("start_time__lte", now).And("end_time__gte", now)

	if storeId > 0 {
		// applicable_stores 是一个 JSON 数组，如 "[1,2,3]"。
		// 空数组 "[]" 表示适用于所有门店。
		// 我们需要查找 storeId 在 applicable_stores 列表中或 applicable_stores 为 "[]" 的活动。
		storeIdStr := fmt.Sprintf("%d", storeId)
		storeCond := orm.NewCondition()
		storeCond = storeCond.Or("applicable_stores", nil).
			Or("applicable_stores", "[]").
			Or("applicable_stores", fmt.Sprintf("[%s]", storeIdStr)).
			Or("applicable_stores__startswith", fmt.Sprintf("[%s,", storeIdStr)).
			Or("applicable_stores__contains", fmt.Sprintf(",%s,", storeIdStr)).
			Or("applicable_stores__endswith", fmt.Sprintf(",%s]", storeIdStr))
		cond = cond.AndCond(storeCond)
	}

	qs := o.QueryTable(new(GroupBuyActivity)).SetCond(cond)

	_, err := qs.OrderBy("sort_order").All(&activities)
	return activities, err
}

// IncreaseSoldCount 增加已售数量
func IncreaseSoldCount(id int64, count int) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(GroupBuyActivity)).Filter("id", id).Update(orm.Params{
		"sold_count": orm.ColValue(orm.ColAdd, count),
		"updated_at": time.Now().Unix(),
	})
	return err
}

// BeforeInsert 在插入前设置创建时间
func (g *GroupBuyActivity) BeforeInsert() {
	g.CreatedAt = time.Now().Unix()
	g.UpdatedAt = time.Now().Unix()
	g.IsDeleted = 0
}

// BeforeUpdate 在更新前设置更新时间
func (g *GroupBuyActivity) BeforeUpdate() {
	g.UpdatedAt = time.Now().Unix()
}

// CheckGroupBuyActivityAccess 检查用户是否有权限访问指定的团购活动
func CheckGroupBuyActivityAccess(activityId int64, franchiseId int64) (bool, error) {
	if franchiseId <= 0 {
		return true, nil // 超级管理员可以访问所有团购活动
	}

	o := orm.NewOrm()
	exist := o.QueryTable(new(GroupBuyActivity)).Filter("id", activityId).Filter("franchise_id", franchiseId).Filter("is_deleted", 0).Exist()
	return exist, nil
}

// GetGroupBuyActivitiesByFranchiseId 根据加盟商ID获取团购活动
func GetGroupBuyActivitiesByFranchiseId(franchiseId int64, page, pageSize int) ([]*GroupBuyActivity, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(GroupBuyActivity))

	qs = qs.Filter("franchise_id", franchiseId).Filter("is_deleted", 0)

	total, _ := qs.Count()

	var activities []*GroupBuyActivity
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&activities)

	return activities, total, err
}
